package com.tiantianyuegou.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.tiantianyuegou.R;
import com.tiantianyuegou.activity.BuyOrAddActivity;
import com.tiantianyuegou.model.ProductModel;
import com.tiantianyuegou.model.StoreModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/1/15.
 */
public class GouwucheAdapter extends BaseAdapter {

    private Context mContext;
    private List<StoreModel> mData;

    private Map<String, Boolean> mRecordChoose = new HashMap<>();//记录勾选状态

    public interface ISelectCouponListener {
        void reCalcuate(List<StoreModel> mData);//重新计算价格

        void deleteProduct(int postition, ProductModel model);//删除商品
    }

    private ISelectCouponListener mListener;

    public void setSelectCouponListener(ISelectCouponListener listener) {
        mListener = listener;
    }

    public GouwucheAdapter(Context context) {
        mContext = context;
        mData = new ArrayList<>();
        ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(mContext));
    }

    public GouwucheAdapter(Context context, List<StoreModel> data) {
        mContext = context;
        mData = data;
    }

    public void setData(List<StoreModel> data) {
        mData = data;
    }

    public Map<String, Boolean> getChoose() {
        return mRecordChoose;
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        final ViewHolder holder = new ViewHolder();
        convertView = LayoutInflater.from(mContext).inflate(R.layout.item_gouwuche_store, null);
        holder.mTxt_store_name = (TextView) convertView.findViewById(R.id.item_gouwuche_store_name);
        holder.mLinear_product = (LinearLayout) convertView.findViewById(R.id.item_confirm_product);
        holder.mGouwuche_store = (LinearLayout) convertView.findViewById(R.id.layout_gouwuche_store);
        holder.mImg_select = (ImageView) convertView.findViewById(R.id.iv_gouwuche_store_img);
        final StoreModel store = mData.get(position);
        holder.mTxt_store_name.setText(store.getStoreName());
        //在动态添加之前先清除之前的view
        holder.mLinear_product.removeAllViews();
        //动态添加产品界面
        for (int i = 0; i < store.getProductModels().size(); i++) {
            final ProductModel model = store.getProductModels().get(i);
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_gouwuche_product, holder.mLinear_product, false);

            ImageView productPic = (ImageView) view.findViewById(R.id.item_confirm_product_img);
            ImageLoader.getInstance().displayImage(model.getUrl(), productPic);

            ((TextView) view.findViewById(R.id.item_gouwuche_product_name)).setText(model.getName());
            ((TextView) view.findViewById(R.id.item_gouwuche_product_price)).setText(model.getPrice());
            ((TextView) view.findViewById(R.id.item_gouwuche_product_spec)).setText(model.getSpec());
            ((TextView) view.findViewById(R.id.item_gouwuche_product_count)).setText("x" + model.getNumber());
            RelativeLayout layout_gouwuche_product = (RelativeLayout) view.findViewById(R.id.layout_gouwuche_product);
            ImageView iv_gouwuche_xiugai = (ImageView) view.findViewById(R.id.iv_gouwuche_xiugai);
            ImageView iv_gouwuche_dele = (ImageView) view.findViewById(R.id.iv_gouwuche_dele);
            final ImageView iv_storeProduct_select = (ImageView) view.findViewById(R.id.iv_gouwuche_storeproduct_img);
            //先判断是否包含该key值
//            if (mRecordChoose.containsKey("p" + model.getTscId())) {
//                if (model.isSelect() || mRecordChoose.get("p" + model.getTscId())) {
//                    iv_storeProduct_select.setImageResource(R.mipmap.select_icon);
//                } else {
//                    iv_storeProduct_select.setImageResource(R.mipmap.unselect_icon);
//                }
//            } else {
            if (model.isSelect()) {
                iv_storeProduct_select.setImageResource(R.mipmap.select_icon);
            } else {
                iv_storeProduct_select.setImageResource(R.mipmap.unselect_icon);
            }
//            }

            //选中某个购物车商品
            layout_gouwuche_product.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (model.isSelect()) {
                        iv_storeProduct_select.setImageResource(R.mipmap.unselect_icon);
                        model.setIsSelect(false);
                        mRecordChoose.put("p" + model.getTscId(), false);
                        // allSelectChange(position);
                    } else {
                        iv_storeProduct_select.setImageResource(R.mipmap.select_icon);
                        model.setIsSelect(true);
                        mRecordChoose.put("p" + model.getTscId(), true);
                        // allSelectChange(position);
                    }

                    //判断是否是在全选状态的临界状态
                    boolean isAllSelect = true;
                    List<ProductModel> list = mData.get(position).getProductModels();
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).isSelect()) {
                            continue;
                        } else {
                            isAllSelect = false;
                            break;
                        }
                    }
                    if (isAllSelect) {
                        mRecordChoose.put("s" + store.getStoreId(), true);
                        holder.mImg_select.setImageResource(R.mipmap.select_icon);
                        mData.get(position).setIsSelect(true);
                    } else {
                        mRecordChoose.put("s" + store.getStoreId(), false);
                        holder.mImg_select.setImageResource(R.mipmap.unselect_icon);
                        mData.get(position).setIsSelect(false);
                    }
                    mListener.reCalcuate(mData);
                }
            });
            //修改点击事件
            iv_gouwuche_xiugai.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, BuyOrAddActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("model", model);
                    intent.putExtras(bundle);
                    intent.putExtra("type", "edit");
                    mContext.startActivity(intent);
                }
            });
            //删除点击事件
            iv_gouwuche_dele.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showpopupwindow();//删除提示框
                }

                private PopupWindow popupWindow = null;

                @SuppressLint("InflateParams")
                private void showpopupwindow() {
                    View view = LayoutInflater.from(mContext).inflate(R.layout.popupwindow_gouwuche,
                            null);
                    TextView txt_confirm = (TextView) view.findViewById(R.id.txt_confirm);
                    txt_confirm.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            mListener.deleteProduct(position, model);
                            popupWindow.dismiss();
                        }
                    });
                    TextView txt_cancel = (TextView) view.findViewById(R.id.txt_cancel);
                    txt_cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            popupWindow.dismiss();
                        }
                    });
                    popupWindow = new PopupWindow(view, ViewPager.LayoutParams.MATCH_PARENT,
                            ViewPager.LayoutParams.MATCH_PARENT, true);
                    popupWindow.setFocusable(true);
                    popupWindow.setOutsideTouchable(true);
                    popupWindow.setBackgroundDrawable(new BitmapDrawable());
                    popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
                }
            });

            holder.mLinear_product.addView(view);

        }
        //选中店铺
        holder.mGouwuche_store.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mData.get(position).isSelect()) {
                    mData.get(position).setIsSelect(false);
                    //  holder.mImg_select.setImageResource(R.mipmap.unselect_icon);
                    selectAllProduct(position, false);
                    mRecordChoose.put("s" + store.getStoreId(), false);
                } else {
                    mData.get(position).setIsSelect(true);
                    //holder.mImg_select.setImageResource(R.mipmap.select_icon);
                    selectAllProduct(position, true);
                    mRecordChoose.put("s" + store.getStoreId(), true);
                }
                mListener.reCalcuate(mData);
                notifyDataSetChanged();
            }
        });
        //先判断是否包含该key值
//        if (mRecordChoose.containsKey("s" + store.getStoreId())) {
//            if (store.isSelect() || mRecordChoose.get("s" + store.getStoreId())) {
//                holder.mImg_select.setImageResource(R.mipmap.select_icon);
//            } else {
//                holder.mImg_select.setImageResource(R.mipmap.unselect_icon);
//            }
//        } else {
        if (store.isSelect()) {
            holder.mImg_select.setImageResource(R.mipmap.select_icon);
        } else {
            holder.mImg_select.setImageResource(R.mipmap.unselect_icon);
        }
//        }


        return convertView;
    }

    //勾选商品的时候，判断是否是所有商品被勾选
    private void allSelectChange(int position) {
        boolean isAllSelect = true;
        List<ProductModel> list = mData.get(position).getProductModels();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isSelect()) {
                continue;
            } else {
                isAllSelect = false;
                break;
            }
        }
        if (isAllSelect) {
            mData.get(position).setIsSelect(true);
        } else {
            mData.get(position).setIsSelect(false);
        }
        notifyDataSetChanged();
    }

    //勾选店铺的时候
    private void selectAllProduct(int position, boolean select) {
        List<ProductModel> list = mData.get(position).getProductModels();
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setIsSelect(select);
            mRecordChoose.put("p" + list.get(i).getTscId(), select);
        }
    }

    class ViewHolder {
        TextView mTxt_store_name;
        ImageView mImg_select;
        LinearLayout mLinear_product, mGouwuche_store;

    }
}
